<?php


namespace Medicina\BackendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Medicina\BackendBundle\Form\PersonaType;
use Symfony\Component\HttpFoundation\Response;

class AsesorController extends Controller {

    public function editAction($id) {

        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('MedicinaKernelBundle:Persona')->find($id);
        $editForm = $this->createForm(new PersonaType(), $entity);


        return $this->render('BackendBundle:Persona:form.html.twig', array(
                    'entity' => $entity,
                    'form' => $editForm->createView(),
                    'type'=>'asesor'
                ));
    }

    public function updateAction($id,$tipo) {
              return $this->editEntity('MedicinaKernelBundle:PersonaAsesora', $id,$tipo);
    }

    private function editEntity($entity, $id,$tipo)  {
        $em = $this->getDoctrine()->getEntityManager();
        $entity = $em->getRepository($entity)->find($id);
        $return = array();
        if (!$entity) {
            $this->createMsgEdit($return,false, $entity,array(array("key"=>"#TipoAsesorType_tipoAsesor", "msj"=>"Error ")));
        } else {      
                try{
                $entity->setTipoAsesor($tipo);
                $em->persist($entity);
                $em->flush();
                $this->createMsgEdit($return, true, $entity);
                  } catch (\PDOException $e) {
                    $this->createMsgEdit($return, false, $entity,array(array("key"=>"#TipoAsesorType_tipoAsesor", "msj"=>"Error ")));
                     
                  }
        
        }
        return $this->createAjaxResponse($return);
    }


    private function createMsgEdit(&$return, $okStatus = false, $entity, $errors=array()) {
        if ($okStatus) {
            $return['status'] = true;
            $return['mensaje'] = "Editado con exito";
            $return['entity'] = $entity->getJsonForAjaxEdit();
           
        } else {
            $return['status'] = false;
            $return['mensaje'] = "Ocurrio un error al intentar editar";
            $return['entity'] = $entity->getJsonForAjaxEdit();
             $return['errors'] =$errors;
        }
        return $return;
    }

    private function createAjaxResponse($return) {
        return new Response(json_encode($return), 200, array('Content-Type' => 'application/json'));
    }

}

?>

